<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>16-图片转为Base64</title>
		<!-- 导入jQuery库 -->
		<script type="text/javascript" src="../../lib/jquery/jquery-1.11.3.min.js" ></script>
	</head>
	<body>
		
		<img id="imgId" src="../../img/iceberg_1x.jpg" />
		<textarea id="textArea" style="height:350px;width:500px;"></textarea><br/>
		<hr />
		<input type="file" id="fid" name="文件上传" />
		<!-- 缩略图 -->
		<img id="img" src="" width="100" height="100">
		<button id="getSL">查看缩略图</button>
		<button id="fbtn">得到上传文件信息</button>
		<script>
			$("#fbtn").click(function(){
				var files = $("#fid");
				console.log("files:",files);
				console.log("files长度:",files.length);
				console.log("files[0]:",files[0]);
				console.log("files[0].files:",files[0].files);
				console.log("files[0].files.length:",files[0].files.length);
				console.log("真正的文件对象 -> files[0].files.[0]:",files[0].files[0]);//这个才是真正的文件对象
				// 获得图片转为 toBase64
			});
			
			$("#getSL").click(function(){
				imgPreview();
//				document.getElementById('img-select').addEventListener('change',imgPreview);
			});
			
			function imgPreview() {
			    var files = $("#fid")[0];
			    var file = files.files[0];
			    var reader = new FileReader();
			    var imageBase64 = "";
			    reader.onload = function() {
//			    	console.log("读取的编码:",reader.result)
					imageBase64 = reader.result;
					console.log("图片的编码：",imageBase64.length);
			        document.getElementById('img').src=imageBase64;//img的id
			        $("#textArea").empty()
			        $("#textArea").text(imageBase64)
			        get(imageBase64)
			    }
			    if (file) {
					reader.readAsDataURL(file);
				} else {
					document.getElementById('img').src= "";
				}
				console.log("上传的文件：",file);
				console.log("图片的编码：",imageBase64); // 这里拿不到的
				console.log("图片的编码：",document.getElementById('img').src);
			}
			
			// 模拟 form 表单请求接口
			function get(_base64){
				let param = {
					type: "10001",
					id: "522301003020100070000018003",
					image_name: "测试图片",
					changer: "测试",
					changer_id: "522301003020100070000018003",
					remark: "备注信息",
					image_type: "image/png",
					image_content: $("#fid")[0].files[0],
					contentType: "multipart/form-data",
				}
				$.ajax({
					type:"post",
					url:"http://127.0.0.1:82/hadmin/api/images/upload",
					// url:"http://127.0.0.1:82/hadmin/api/images/upload",
					async:true,
					data: param,
					dataType:"json",
					cache: false,  
		            processData: false,  
		            contentType: "multipart/form-data",
					success: function (data) {
						console.log(data)
					},
					error: function (err){
						console.log(err)
					}
				});
				
			}
		</script>
		
	</body>
</html>
